package commons

import (
	"encoding/json"
	"fmt"
)

const (
	//AccessTokenURL 获取access_token的接口
	getAPIDomainIPURL = "https://qyapi.weixin.qq.com/cgi-bin/get_api_domain_ip"

	getCallbackIPURL = "https://qyapi.weixin.qq.com/cgi-bin/getcallbackip"
)

// APIDomainIPResp 企业微信服务器IP返回结果
type APIDomainIPResp struct {
	CommonError
	IPList []string `json:"ip_list"`
}

// GetCallBackIP 获取企业微信回调IP地址列表
// 参考https://open.work.weixin.qq.com/api/doc/90000/90135/90930#3.3%20%E8%8E%B7%E5%8F%96%E4%BC%81%E4%B8%9A%E5%BE%AE%E4%BF%A1%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%9A%84ip%E6%AE%B5
func GetCallBackIP(accessToken string) ([]string, error) {
	url := fmt.Sprintf("%s?access_token=%s", getCallbackIPURL, accessToken)
	body, err := HTTPGet(url)
	if err != nil {
		return nil, err
	}
	var resp APIDomainIPResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return nil, err
	}
	// 如果api没有返回错误，那么errcode默认为0，如果errcode不为0，则表示返回了错误
	if resp.ErrCode != 0 {
		err = fmt.Errorf("GetCallBackIP error : errcode=%v , errormsg=%v", resp.ErrCode, resp.ErrMsg)
		return nil, err
	}

	return resp.IPList, nil

}

// GetAPIDomainIP 获取企业微信API域名IP段
// 参考https://open.work.weixin.qq.com/api/doc/90000/90135/92520
func GetAPIDomainIP(accessToken string) ([]string, error) {
	url := fmt.Sprintf("%s?access_token=%s", getAPIDomainIPURL, accessToken)
	body, err := HTTPGet(url)
	if err != nil {
		return nil, err
	}
	var resp APIDomainIPResp
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return nil, err
	}
	// 出错返回码，为0表示成功，非0表示调用失败
	if resp.ErrCode != 0 {
		err = fmt.Errorf("GetAPIDomainIP error : errcode=%v , errormsg=%v", resp.ErrCode, resp.ErrMsg)
		return nil, err
	}

	return resp.IPList, nil
}
